package com.jyb.qiyefuwu.viewmodel;

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.util.Pair;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jyb.qiyefuwu.api.EnterpriseServiceAPIManager;
import com.jyb.qiyefuwu.entity.MakeOverOrderEntity;
import com.jyb.qiyefuwu.entity.OderDetailsEntity;
import com.jyb.qiyefuwu.eventmodel.UpdateSaleListEvent;
import com.sgb.link.router.PathCapital;
import com.sgb.net.entity.BaseEntity;
import com.sgb.net.entity.ListResponse;
import com.swgk.core.common.base.BaseViewModel;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SaleListViewModel extends BaseViewModel {
    public int orderStatus;//通订单:1待结单 2待支付 3已关闭 4交易中
    public int buyerOrSeller;//0销售订单 1采购订单
    public int orderType;// 1表示商标转让 2表示专利转让 3表示版权转让
    public boolean isloadmore;
    private int page = 1;
    public MutableLiveData<List<MakeOverOrderEntity>> listdata = new MutableLiveData<>(new ArrayList<>());
    public MutableLiveData<Long> delete_item = new MutableLiveData<>();
    public MutableLiveData<Long> delete_fail = new MutableLiveData<>();
    public MutableLiveData<Long> conFrimOrderFail = new MutableLiveData<>();
    public MutableLiveData<Long> closeFail = new MutableLiveData<>();
    public MutableLiveData<String> payStatus = new MutableLiveData<>();
    public int process_type = -1; //开户状态， 只有2和4才可以确认接单


    public MakeOverOrderEntity choiceItem = null;
    public OderDetailsEntity oderDetailsEntity = null;
    public String applyId = "";//审批流程id;
    public MutableLiveData<Integer> approvestats = new MutableLiveData<>();//-2 待提交审批 -1 待审核 0拒绝 1通过 2不需要审核未提交资金中心订单 3不需要审核已提交资金中心订单

    public SaleListViewModel(@NonNull @NotNull Application application) {
        super(application);
    }

    public void getData(boolean isloadmore) {
        this.isloadmore = isloadmore;
        page = isloadmore ? page + 1 : 1;
        Map<String, Object> map = new HashMap<>();
        map.put("buyerOrSeller", buyerOrSeller == 0 ? 2 : 1);//销售订单为卖方传2：采购订单为买方传1
        map.put("buyerPublishType", SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0));
        map.put("limit", 20);
        map.put("orderStatus", orderStatus);
        map.put("pageSize", page);
        map.put("sellerOrBuyerNo", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 0 ? SharedPreferenceUtil.USER_NO : SharedPreferenceUtil.COMPANY_NO, ""));
        mLoading.postValue(BaseViewModel.SHOW_LODING);
        Call<BaseEntity<ListResponse<List<MakeOverOrderEntity>>>> call = orderType == 1 ? EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().gettradeMarkOrderList(map) : orderType == 2 ? EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().getpatentOrderList(map) : EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().getcopyrightOrderList(map);
        call.enqueue(new Callback<BaseEntity<ListResponse<List<MakeOverOrderEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ListResponse<List<MakeOverOrderEntity>>>> call, Response<BaseEntity<ListResponse<List<MakeOverOrderEntity>>>> response) {
                mLoading.postValue(BaseViewModel.DISMISS_LODING);
                if (response.body() == null || response.body().data() == null) {
                    return;
                }
                if (response.body().getState().equals("ok")) {
                    if (response.body().data().getList() != null) {
                        listdata.postValue(response.body().data().getList());
                    }
                } else {
                    mToast.postValue(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse<List<MakeOverOrderEntity>>>> call, Throwable t) {
                mLoading.postValue(BaseViewModel.DISMISS_LODING);
                mToast.postValue(t.getMessage());
            }
        });
    }

    /**
     * 关闭订单
     */
    public void ColoseOrder(String orderid, String closeContent, boolean iscolose) {
        mLoading.postValue(BaseViewModel.SHOW_LODING);
        String no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 0 ? SharedPreferenceUtil.USER_NO : SharedPreferenceUtil.COMPANY_NO, "");
        mLoading.postValue(BaseViewModel.SHOW_LODING);
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().orderclosing(no, orderid, closeContent, buyerOrSeller == 0 ? 2 : 1).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                mLoading.postValue(BaseViewModel.DISMISS_LODING);
                if (response.body() == null) {
                    return;
                }

                if (response.body().getState().equals("ok")) {
                    delete_item.postValue(Long.parseLong(orderid));
                    mToast.postValue(iscolose ? "订单已关闭" : "订单已取消");
                } else {
                    getData(false);
                    closeFail.postValue(Long.parseLong(orderid));
                    mToast.postValue(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                mLoading.postValue(BaseViewModel.DISMISS_LODING);
                mToast.postValue(t.getMessage());
            }
        });
    }

    /**
     * 删除订单
     */
    public void deleteOrder(String orderid) {
        mLoading.postValue(BaseViewModel.SHOW_LODING);
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().DeleteOrder("v1/app/enterpriseServices/order/" + orderid + "/" + (buyerOrSeller == 0 ? 2 : 1)).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                mLoading.postValue(BaseViewModel.DISMISS_LODING);
                if (response.body() == null) {
                    return;
                }

                if (response.body().getState().equals("ok")) {

                    delete_item.postValue(Long.parseLong(orderid));
                    mToast.postValue("删除成功");

                } else {
                    getData(false);
                    delete_fail.postValue(Long.parseLong(orderid));
                    mToast.postValue(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                mLoading.postValue(BaseViewModel.DISMISS_LODING);
                mToast.postValue(t.getMessage());
            }
        });
    }

    /**
     * 获取用户开户信息
     */
    public void getUserWallet() {
        if (buyerOrSeller != 0 || orderStatus != 1) {//销售订单，待接单状态下获取

            return;
        }
        EnterpriseServiceAPIManager.getInstance().getUserCenterPayAPI().getUserWalletMessage().enqueue(new Callback<BaseEntity<Object>>() {
            @Override
            public void onResponse(Call<BaseEntity<Object>> call, Response<BaseEntity<Object>> response) {

                if (response.body() == null) {
                    return;
                }

                if (response.body().getState().equals("ok")) {
                    if (response.body().getData() != null) {
                        try {

                            JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(response.body().getData()));
                            if (jsonObject.get("process") != null) {
                                process_type = jsonObject.getInteger("process");
                            }
                        } catch (Exception e) {
                            mToast.postValue(e.getMessage());
                        }
                    }

                } else {
                    mToast.postValue(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {

                mToast.postValue(t.getMessage());
            }
        });
    }


    /**
     * 确认接单
     */
    public void ConFrimOrder(String orderId) {
        mLoading.postValue(BaseViewModel.SHOW_LODING);
        String no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 0 ? SharedPreferenceUtil.USER_NO : SharedPreferenceUtil.COMPANY_NO, "");
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().ConFrimOrder(orderId, no).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                mLoading.postValue(BaseViewModel.DISMISS_LODING);
                if (response.body() == null) {
                    return;
                }

                if (response.body().getState().equals("ok")) {
                    mToast.postValue("接单成功");
                    delete_item.postValue(Long.parseLong(orderId));
                } else {
                    getData(false);
                    conFrimOrderFail.postValue(Long.parseLong(orderId));
                    mToast.postValue(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                mLoading.postValue(BaseViewModel.DISMISS_LODING);
                mToast.postValue(t.getMessage());
            }
        });
    }


    public void getOrderStatus(int type) {
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().getOrderStatus(type == 0 ? choiceItem.getOrderId() : oderDetailsEntity.getOrderId(), SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, ""), "enterpriseOrder").enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals("ok")) {
                    String data = JSONObject.toJSONString(response.body().getData());
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsonObject = JSON.parseObject(data);
                        if (jsonObject.get("applyId") != null) {
                            applyId = jsonObject.getString("applyId");
                        }else{
                            applyId = "";
                        }
                        if (jsonObject.get("examinationId") != null) {
                            if (type > 0) {
                                oderDetailsEntity.setExaminationId(jsonObject.getString("examinationId"));
                            } else {
                                choiceItem.setExaminationId(jsonObject.getString("examinationId"));
                            }

                        }
                        if (jsonObject.get("payOrderCount") != null) {
                            if (type > 0) {
                                oderDetailsEntity.setPayOrderCount(jsonObject.getInteger("payOrderCount"));
                            } else {
                                choiceItem.setPayOrderCount(jsonObject.getInteger("payOrderCount"));
                            }
                        }
                        if (jsonObject.get("orderStatus") != null) {
                            switch (jsonObject.getInteger("orderStatus")) {

                                case 0:
                                    getCompanyType(type);
                                    break;
                                case 1:

                                    getApprovestats(type);

                                    break;
                                case 2:
                                    if (type == 0) {
                                        //列表
                                        if (choiceItem.getPayOrderCount() > 0) {
                                            approvestats.postValue(5);
                                        } else {
                                            approvestats.postValue(4);
                                        }
                                    } else {
                                        //详情
                                        if (oderDetailsEntity.getPayOrderCount() > 0) {
                                            approvestats.postValue(5);
                                        } else {
                                            approvestats.postValue(4);
                                        }
                                    }
                                    break;
                            }
                        }
                    }
                } else {
                    mToast.postValue(response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {

            }
        });
    }


    /**
     * 获取公司是否需要审批
     */

    public void getCompanyType(int type) {

        String companyno = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyno);
        map.put("type", "enterpriseOrder");
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().getCompanyType(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {

                if (response.body() == null) {
                    return;
                }

                if (response.body().getState().equals("ok")) {
                    String data = JSONObject.toJSONString(response.body().getData());
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsonObject = JSON.parseObject(data);
                        if (jsonObject.get("applyId") != null) {
                            applyId = jsonObject.getString("applyId");
                        }
                        if (jsonObject.get("status") != null) {
                            if (!TextUtils.isEmpty(applyId) && "1".equals(jsonObject.getString("status"))) {//需要审批
                                if (type == 0) {
                                    //列表
                                    if (!TextUtils.isEmpty(choiceItem.getExaminationId())) {//是否提交需要审批的内容
                                        getApprovestats(type);//获取当前审批状态
                                    } else {//待提交审批内容
                                        approvestats.postValue(-2);
                                    }
                                } else {
                                    //详情
                                    if (!TextUtils.isEmpty(oderDetailsEntity.getExaminationId())) {//是否提交需要审批的内容
                                        getApprovestats(type);//获取当前审批状态
                                    } else {//待提交审批内容
                                        approvestats.postValue(-2);
                                    }
                                }
                            } else {//不需要审批
                                if (type == 0) {
                                    //列表
                                    if (choiceItem.getPayOrderCount() > 0) {
                                        approvestats.postValue(5);
                                    } else {
                                        approvestats.postValue(4);
                                    }
                                } else {
                                    //详情
                                    if (oderDetailsEntity.getPayOrderCount() > 0) {
                                        approvestats.postValue(5);
                                    } else {
                                        approvestats.postValue(4);
                                    }
                                }

                            }
                        }
                    }
                } else {
                    mToast.postValue(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {

                mToast.postValue(t.getMessage());
            }
        });
    }


    /**
     * 获取审批状态
     */
    public void getApprovestats(int type) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", type == 0 ? choiceItem.getExaminationId() : oderDetailsEntity.getExaminationId());
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().getApproveStatus(map).enqueue(new Callback<BaseEntity<String>>() {
            @Override
            public void onResponse(Call<BaseEntity<String>> call, Response<BaseEntity<String>> response) {

                if (response.body() == null) {
                    return;
                }

                if (response.body().getState().equals("ok")) {
                    if (!TextUtils.isEmpty(response.body().getData())) {
                        try {

                            if ("0".equals(response.body().getData()) &&"".equals(applyId)) {
                                if (type == 0) {
                                    //列表
                                    if (choiceItem.getPayOrderCount() > 0) {
                                        approvestats.postValue(5);
                                    } else {
                                        approvestats.postValue(4);
                                    }
                                } else {
                                    //详情
                                    if (oderDetailsEntity.getPayOrderCount() > 0) {
                                        approvestats.postValue(5);
                                    } else {
                                        approvestats.postValue(4);
                                    }
                                }
                            } else {
                                approvestats.postValue(Integer.parseInt(response.body().getData()));
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.e("message", "获取审批状态结果值报错");
                        }
                    }
                } else {
                    mToast.postValue(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity<String>> call, Throwable t) {
                mToast.postValue(t.getMessage());
            }
        });
    }

    /**
     * 待付款-生成待付订单-公司团队-不需要审批
     */
    public void CreatePayOrder(int type) {
        String no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");

        Map<String, Object> map = new HashMap<>();
        map.put("creator", no);
        map.put("isFeePayer", 1);//卖家是否是手续费承担方 1 是，0 否
        map.put("matters", "企业服务");//付款实事项
        map.put("method", "在线付款");//付款方式
        map.put("money", type == 0 ? choiceItem.getDealPrice() : oderDetailsEntity.getDealPrice());//付款金额
        map.put("orderId", type == 0 ? choiceItem.getOrderId() : oderDetailsEntity.getOrderId());//业务订单id
        map.put("orderType", "0006");//订单类型 0001 材料订单

        if (type == 0) {
            if (choiceItem.getPublishType() == 1) {
                map.put("payeeAccountName", choiceItem.getSellerName());//收款账户名称
                map.put("payeeCompany", choiceItem.getSellerNo());

            } else {
                map.put("payeeName", choiceItem.getSellerName());//收款账户名称
                map.put("payeeNo", choiceItem.getAgentNo());
                map.put("payeeAccountName", choiceItem.getSellerName());//收款账户名称
            }
        } else {
            if (oderDetailsEntity.getPublishType().equals("1")) {
                map.put("payeeAccountName", oderDetailsEntity.getSellerName());//收款账户名称
                map.put("payeeCompany", oderDetailsEntity.getSellerNo());

            } else {
                map.put("payeeName", oderDetailsEntity.getSellerName());//收款账户名称
                map.put("payeeNo", oderDetailsEntity.getAgentNo());
                map.put("payeeAccountName", oderDetailsEntity.getSellerName());//收款账户名称
            }
        }

        map.put("tradeType", 2);
        map.put("payerCompany", type == 0 ? choiceItem.getBuyersNo() : oderDetailsEntity.getBuyersNo());
        map.put("payerAccountName", type == 0 ? choiceItem.getBuyersName() : oderDetailsEntity.getBuyersName());


//        map.put("account",choiceItem.getBuyersName());
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().createPayOrder(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {

                if (response.body() == null) {
                    return;
                }
                if (choiceItem != null) {
                    getData(false);
                } else {
                    EventBus.getDefault().post(new UpdateSaleListEvent(2, 1));
                }
                if (response.body().getState().equals("ok")) {

                } else if ("管理员已经开启订单付款审批流程".equals(response.body().getMsg())) {
                    approvestats.postValue(6);
                } else {
                    mToast.postValue(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                mToast.postValue(t.getMessage());
            }
        });
    }


    /**
     * 待付款-生成待付订单-个人
     */

    public void CreatePayOrderForUser(int type) {

        int payordercpunt = type == 0 ? choiceItem.getPayOrderCount() : oderDetailsEntity.getPayOrderCount();
        if (payordercpunt > 0) {
            if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 1) {
                ActivityJump.startActivity(PathCapital.PayDealActivity,
                        Pair.create("orderId", type == 0 ? choiceItem.getOrderId() : oderDetailsEntity.getOrderId()));
            } else {
                ActivityJump.startActivity(PathCapital.PersonPayActivity,
                        Pair.create("orderId", type == 0 ? choiceItem.getOrderId() : oderDetailsEntity.getOrderId()));

            }
        } else {
            String no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 0 ? SharedPreferenceUtil.USER_NO : SharedPreferenceUtil.COMPANY_NO, "");
            Map<String, Object> map = new HashMap<>();
            map.put("orderChannel", "2");
            map.put("isFeePayer", "1");//卖家是否是手续费承担方 1 是，0 否
            map.put("remark", "企服交易");//付款实事项
            map.put("amount", type == 0 ? choiceItem.getDealPrice() : oderDetailsEntity.getDealPrice());//付款金额
            map.put("orderId", type == 0 ? choiceItem.getOrderId() : oderDetailsEntity.getOrderId());//业务订单id
            map.put("orderType", "2");//订单类型 0001 材料订单
            if (type == 0 ? choiceItem.getPublishType() == 1 : oderDetailsEntity.getPublishType().equals("1")) {
                map.put("payeeCompanyName", type == 0 ? choiceItem.getSellerName() : oderDetailsEntity.getSellerName());//收款账户名称
                map.put("payeeCompany", type == 0 ? choiceItem.getSellerNo() : oderDetailsEntity.getSellerNo());
            } else {
                map.put("payeeName", type == 0 ? choiceItem.getSellerName() : oderDetailsEntity.getSellerName());//收款账户名称
                map.put("payee", type == 0 ? choiceItem.getAgentNo() : oderDetailsEntity.getAgentNo());
            }
            map.put("tradeType", "12");
            map.put("payerName", type == 0 ? choiceItem.getBuyersName() : oderDetailsEntity.getBuyersName());
            Log.e("json", new Gson().toJson(map));
            EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().createPayOrderforUser(map).enqueue(new Callback<BaseEntity<String>>() {
                @Override
                public void onResponse(Call<BaseEntity<String>> call, Response<BaseEntity<String>> response) {

                    if (response.body() == null) {
                        return;
                    }

                    if (response.body().getState().equals("ok")) {
                        if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 1) {
                            ActivityJump.startActivity(PathCapital.PayDealActivity,
                                    Pair.create("orderId", type == 0 ? choiceItem.getOrderId() : oderDetailsEntity.getOrderId()));
                        } else {
                            ActivityJump.startActivity(PathCapital.PersonPayActivity,
                                    Pair.create("orderId", type == 0 ? choiceItem.getOrderId() : oderDetailsEntity.getOrderId()));

                        }
                        payStatus.postValue("交易成功");
                    } else {
                        if (choiceItem != null) {
                            getData(false);
                        } else {
                            EventBus.getDefault().post(new UpdateSaleListEvent(2, 1));
                        }
                        mToast.postValue(response.body().getMsg());
                    }

                }

                @Override
                public void onFailure(Call<BaseEntity<String>> call, Throwable t) {
                    mToast.postValue(t.getMessage());
                }
            });
        }
    }


    /**
     * 买方确认完成订单
     */
    public void confirmOderComplete(int type){
        EnterpriseServiceAPIManager.getInstance().getUserCenterAPI().confirmOrdercomplete(type == 0 ? choiceItem.getOrderId()+"" : oderDetailsEntity.getOrderId()+"").enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {

                if (response.body() == null) {
                    return;
                }

                if (response.body().getState().equals("ok")) {
                    delete_item.postValue(Long.parseLong(type == 0 ? choiceItem.getOrderId()+"" : oderDetailsEntity.getOrderId()+""));
                } else {//失败异步刷新列表
                    if (choiceItem != null) {
                        getData(false);
                    } else {
                        EventBus.getDefault().post(new UpdateSaleListEvent(4, 1));
                    }
                    mToast.postValue(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                mToast.postValue(t.getMessage());
            }
        });
    }

}
